package model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


/**
 *
 */
class XMLContentHandler extends DefaultHandler {
    private List uebungen;
    private Uebung uebung;
    private Ressource ressource;
    private String currentValue;
    
    public XMLContentHandler() {
        this.uebungen = new ArrayList<Uebung>();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        if(localName.equals("uebung")) {
            this.uebung = new Uebung();
            this.uebung.setNumber(Integer.parseInt(atts.getValue("nr")));
        }
        
        if(localName.equals("ressource")) {
            if(this.uebung != null){
                this.ressource = new Ressource();
            }
        }
        
        if(localName.equals("datei")) {
            if(this.uebung != null){
                String pfad = atts.getValue("pfad");
                
                if(this.ressource != null){
                    this.ressource.setUrl(pfad);
                } else {
                    this.uebung.setUrl(pfad);
                }
            }
        }

    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(localName.equals("uebung")) {
            this.uebungen.add(this.uebung);
            this.uebung = null;
        }
        
        if(localName.equals("ressource")) {
            if(this.ressource != null){
                this.uebung.addRessource(this.ressource);
                this.ressource = null;
            }
        }
        
                
        if(localName.equals("label")) {
            if(this.uebung != null){
                if(this.ressource != null){
                    this.ressource.setLabel(this.currentValue);
                } else {
                    this.uebung.setLabel(this.currentValue);
                }
            }
        }
        
        if(localName.equals("name")) {
            if(this.ressource != null){
                this.ressource.setName(this.currentValue);
            }
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        this.currentValue = new String(ch, start, length);
    }

    public List getUebungen() {
        return Collections.unmodifiableList(this.uebungen);
    }

}
